package com.cn.algorithm.two.back.test;

public class EightQueenJ {

    public static void main(String[] args) {
        new EightQueenJ().queen(8);
    }

    int[] cols;

    int ways;

    public void queen(int n) {
        if (n <= 0) {
            return;
        }
        cols = new int[n];
        row(0);
        System.out.println(ways);
    }

    public void row(int row) {
        if (row == cols.length) {
            ways++;
            return;
        }
        for (int i = 0; i < cols.length; i++) {
            if (isValid(row, i)) {
                cols[row] = i;
                row(row + 1);
            }
        }
    }

    public boolean isValid(int row, int col) {
        for (int i = 0; i < row; i++) {
            if (cols[i] == col) {
                return false;
            }
            if ((row - i) == Math.abs(cols[i] - col)) {
                return false;
            }
        }
        return true;
    }
}
